package org.convallaria.system.biz.controller.auth;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.convallaria.framework.common.result.ApiResult;
import org.convallaria.framework.security.annotation.Anonymous;
import org.convallaria.framework.security.config.SecurityProperties;
import org.convallaria.framework.security.service.TokenService;
import org.convallaria.system.biz.entity.dto.CaptchaDTO;
import org.convallaria.system.biz.entity.dto.LoginDTO;
import org.convallaria.system.biz.entity.dto.TokenDTO;
import org.convallaria.system.biz.service.auth.AuthService;
import org.convallaria.system.biz.service.auth.CaptchaService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 认证控制器
 *
 * @author convallaria
 * @since 1.0.0
 */
@Tag(name = "认证管理", description = "登录、登出、刷新Token等认证相关接口")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;
    private final TokenService tokenService;
    private final CaptchaService captchaService;
    private final SecurityProperties securityProperties;

    /**
     * 生成验证码
     */
    @Anonymous
    @Operation(summary = "生成验证码", description = "生成图形验证码")
    @GetMapping("/captcha")
    public ApiResult<CaptchaDTO> generateCaptcha() {
        return ApiResult.success(captchaService.generateCaptcha());
    }

    @Anonymous
    @Operation(summary = "用户登录", description = "用户通过用户名密码登录系统")
    @PostMapping("/login")
    public ApiResult<TokenDTO> login(
            @Parameter(description = "登录信息", required = true)
            @Validated @RequestBody LoginDTO loginDTO) {
        return ApiResult.success(authService.login(loginDTO));
    }

    @Operation(summary = "用户登出")
    @PostMapping("/logout")
    public ApiResult<Void> logout(@RequestHeader(required = false) String authorization) {
        String token = null;
        if (authorization != null && authorization.startsWith(securityProperties.getJwt().getPrefix())) {
            token = authorization.substring(securityProperties.getJwt().getPrefix().length());
        }
        authService.logout(token);
        return ApiResult.success();
    }

    @Anonymous
    @Operation(summary = "刷新Token")
    @PostMapping("/refresh")
    public ApiResult<TokenDTO> refreshToken(@RequestParam String refreshToken) {
        return ApiResult.success(authService.refreshToken(refreshToken));
    }

    @Operation(summary = "获取当前用户信息")
    @GetMapping("/userinfo")
    public ApiResult<Object> getUserInfo() {
        return ApiResult.success(authService.getCurrentUserInfo());
    }

    @Operation(summary = "获取当前用户详细信息")
    @GetMapping("/userinfo/detail")
    public ApiResult<Map<String, Object>> getUserDetailInfo() {
        return ApiResult.success(authService.getCurrentUserDetailInfo());
    }

    @Operation(summary = "获取当前用户菜单树")
    @GetMapping("/menus")
    public ApiResult<Object> getCurrentUserMenus() {
        return ApiResult.success(authService.getCurrentUserMenus());
    }

    @Operation(summary = "获取当前用户权限列表")
    @GetMapping("/permissions")
    public ApiResult<Object> getCurrentUserPermissions() {
        return ApiResult.success(authService.getCurrentUserPermissions());
    }

//    @Operation(summary = "验证Token是否有效", description = "验证Token是否有效并返回用户信息")
//    @GetMapping("/validate")
//    public ApiResult<Map<String, Object>> validateToken(@RequestParam String token) {
//        boolean isValid = tokenService.validateToken(token);
//        SecurityUser user = tokenService.getTokenUser(token);
//
//        Map<String, Object> result = new HashMap<>();
//        result.put("valid", isValid);
//        if (isValid && user != null) {
//            result.put("userInfo", Map.of(
//                "userId", user.getUserId(),
//                "username", user.getUsername(),
//                "tenantId", user.getTenantId()
//            ));
//        }
//        result.put("message", isValid ? "Token有效" : "Token无效或已过期");
//        return ApiResult.success(result);
//    }
//
//    @Operation(summary = "修改密码")
//    @PostMapping("/change-password")
//    public ApiResult<Map<String, Object>> changePassword(
//            @RequestParam String oldPassword,
//            @RequestParam String newPassword) {
//        Map<String, Object> result = new HashMap<>();
//        boolean success = authService.changePassword(oldPassword, newPassword);
//        result.put("success", success);
//        result.put("message", success ? "密码修改成功" : "密码修改失败");
//        return ApiResult.success(result);
//    }
//
//    @Operation(summary = "重置密码")
//    @PostMapping("/reset-password")
//    @RequiresPermissions("system:user:resetPwd")
//    public ApiResult<Map<String, Object>> resetPassword(
//            @RequestParam Long userId,
//            @RequestParam String newPassword) {
//        Map<String, Object> result = new HashMap<>();
//        boolean success = authService.resetPassword(userId, newPassword);
//        result.put("success", success);
//        result.put("message", success ? "密码重置成功" : "密码重置失败");
//        return ApiResult.success(result);
//    }
//
//    @Operation(summary = "检查用户权限")
//    @GetMapping("/check-permission")
//    public ApiResult<Map<String, Object>> checkPermission(@RequestParam String permission) {
//        Map<String, Object> result = new HashMap<>();
//        result.put("hasPermission", authService.hasPermission(permission));
//        return ApiResult.success(result);
//    }
//
//    @Operation(summary = "检查用户角色")
//    @GetMapping("/check-role")
//    public ApiResult<Map<String, Object>> checkRole(@RequestParam String role) {
//        Map<String, Object> result = new HashMap<>();
//        result.put("hasRole", authService.hasRole(role));
//        return ApiResult.success(result);
//    }
//
//    @Operation(summary = "获取用户登录历史")
//    @GetMapping("/login-history")
//    public ApiResult<Object> getUserLoginHistory(
//            @RequestParam Long userId,
//            @RequestParam(defaultValue = "1") Integer pageNum,
//            @RequestParam(defaultValue = "10") Integer pageSize) {
//        return ApiResult.success(authService.getUserLoginHistory(userId, pageNum, pageSize));
//    }
//
//    @Operation(summary = "获取在线用户列表")
//    @GetMapping("/online-users")
//    @RequiresPermissions("system:monitor:online")
//    public ApiResult<Object> getOnlineUsers() {
//        return ApiResult.success(authService.getOnlineUsers());
//    }
//
//    @Operation(summary = "强制用户下线")
//    @PostMapping("/force-logout")
//    @RequiresPermissions("system:monitor:online")
//    public ApiResult<Map<String, Object>> forceLogout(@RequestParam Long userId) {
//        Map<String, Object> result = new HashMap<>();
//        boolean success = authService.forceLogout(userId);
//        result.put("success", success);
//        result.put("message", success ? "用户已强制下线" : "强制下线失败");
//        return ApiResult.success(result);
//    }



    // ==================== Token管理相关接口 ====================

//    @Operation(summary = "获取用户当前Token", description = "获取用户当前的Token")
//    @GetMapping("/token/user/{userId}")
//    public ApiResult<Map<String, Object>> getUserToken(
//            @Parameter(description = "用户ID", example = "1")
//            @PathVariable Long userId) {
//
//        String currentToken = tokenService.getUserCurrentToken(userId);
//        boolean hasValidToken = tokenService.hasValidToken(userId);
//
//        Map<String, Object> result = new HashMap<>();
//        result.put("userId", userId);
//        result.put("currentToken", currentToken);
//        result.put("hasValidToken", hasValidToken);
//        result.put("message", hasValidToken ? "用户有有效Token" : "用户没有有效Token");
//
//        return ApiResult.success(result);
//    }
//
//    @Operation(summary = "延长Token过期时间", description = "延长指定Token的过期时间")
//    @PostMapping("/token/extend")
//    public ApiResult<Map<String, Object>> extendToken(
//            @Parameter(description = "JWT Token", example = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...")
//            @RequestParam String token) {
//
//        try {
//            tokenService.extendTokenExpiration(token);
//            Map<String, Object> result = new HashMap<>();
//            result.put("success", true);
//            result.put("message", "Token过期时间延长成功");
//            result.put("token", token);
//            return ApiResult.success(result);
//        } catch (Exception e) {
//            Map<String, Object> result = new HashMap<>();
//            result.put("success", false);
//            result.put("message", "延长Token过期时间失败: " + e.getMessage());
//            return ApiResult.error("延长Token过期时间失败: " + e.getMessage());
//        }
//    }
//
//    @Operation(summary = "清理过期Token", description = "清理所有过期的Token")
//    @PostMapping("/token/clean")
//    public ApiResult<Map<String, Object>> cleanExpiredTokens() {
//        try {
//            long cleanedCount = tokenService.cleanExpiredTokens();
//            Map<String, Object> result = new HashMap<>();
//            result.put("success", true);
//            result.put("cleanedCount", cleanedCount);
//            result.put("message", "清理完成，共清理 " + cleanedCount + " 个过期Token");
//            return ApiResult.success(result);
//        } catch (Exception e) {
//            return ApiResult.error("清理过期Token失败: " + e.getMessage());
//        }
//    }

}
